<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>案例_验证码倒计时</title>
  <style>
    .form {
      width: 600px;
      margin: 100px auto;
    }

    .row {
      width: 100%;
      display: flex;
      border-top: 1px solid #0094ff;
      border-bottom: 1px solid #0094ff;
    }

    .cols-1 {
      flex: 1;
    }

    .cols-2 {
      flex: 2;
    }

    .cell {
      border-left: 1px solid #0094ff;
      padding: 10px 6px;
      line-height: 42px;
      text-align: center;
    }

    .cell:last-child {
      border-right: 1px solid #0094ff;
    }

    .text {
      width: 268px;
      height: 30px;
      padding: 4px;
    }

    .btn {
      height: 38px;
      width: 200px;
    }
  </style>
</head>

<body>
  <div class="form">
    <div class="row">
      <div class="cell cols-1">请输入手机号码</div>
      <div class="cell cols-2">
        <input type="text" class="text" id="phone">
      </div>
      <div class="cell cols-1">
        <input type="button" class="btn" value="获取验证码" id="getCode" disabled>
      </div>
    </div>
  </div>
</body>
<script>
  let phone = document.querySelector('#phone')
  let getCode = document.querySelector('#getCode')
  let reghm = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/

  phone.onblur = () => {
    if (reghm.test(phone.value)) {
      getCode.disabled = false

    } else {
      getCode.disabled = true
    }
  }
  getCode.onclick = () => {
    var times = 4
    times--
      getCode.value = `倒计时${times}`
      getCode.disabled = true
    var time = setInterval(function () {
      getCode.disabled = true
      times--
      getCode.value = `倒计时${times}`
      if (times === 0) {
        getCode.disabled = false
        getCode.value = '获取验证码'
        clearInterval(time)
      }
    }, 1000)

  }
</script>

</html>